using System;
using Domain.Dto;
using Domain.Interface;
using Domain.Model;
using Gmmy.DomainExtension;
using Gmmy.Utility;
using Infrastructure.Repository.DataContext;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Domain.Dto.Role;
using Gmmy.RepositoryExtension;
using Gmmy.Utility.Extensions;
using Microsoft.EntityFrameworkCore;

namespace Infrastructure.Repository.Repository.Sql
{
    public class RoleRepository : RepositoryBase<Role>, IRoleRepository
    {
        public RoleRepository(IDataBaseFactory<EfContext> databaseFactory)
            : base(databaseFactory)
        {

        }

		/// <summary>
        /// 获取角色表列表
        /// </summary>
        /// <param name="input"></param>
        /// <param name="specification"></param>
        /// <returns></returns>
        public async Task<EntityList<RoleListDto>> GetList(RoleListInput input,
            ISpecification<RoleListInput> specification)
        {
            var result = new EntityList<RoleListDto>();
               var query = (from a in dbset
                select new RoleListInput()
                {
                    ID = a.ID,
                    RoleName = a.RoleName,
                    Remark = a.Remark,
                    Sort = a.Sort,
                    CreateTime = a.CreateTime,
                    IsDeleted = a.IsDeleted,
                }).Where(specification.SatisfiedBy());
            if (input.OrderParm == null || !input.OrderParm.Any())
            {
                input.OrderParm = new Dictionary<string, string> {{ "Sort", "ASC"}};
            }
            query = DataSort(query, input.OrderParm);
            var data = await FindAllAsyncAsQuery(query, input.PageIndex, input.PageSize);
            if (data.Data.Any())
            {
                result = data.MapTo<EntityList<RoleListDto>, EntityList<RoleListInput>>();
            }
            return result;
        }

        public async Task<RoleDetailDto> GetRoleDetail(Guid id)
        {
            var query = (from a in dbset.Where(x => !x.IsDeleted && x.ID == id)
                let action = (from b in DataContext.Set<RoleModuleRelation>().Where(x => x.RoleId == a.ID && !x.IsDeleted)
                    join d in DataContext.Set<ModuleAction>().Where(x=>!x.IsDeleted) on b.ActionId equals d.ID
                    select d.ID)
                select new RoleDetailDto
                {
                    ID = a.ID,
                    RoleName = a.RoleName,
                    Remark = a.Remark,
                    Sort = a.Sort,
                    ActionList = action
                });
            return await query.FirstOrDefaultAsync();
        }
    }
}
